import Vue from 'vue'
import Vuex from 'vuex'
import home from './modules/home'
import course from './modules/course'
import {fetchUser,isValidateUser} from '@/api/login.js'
import * as types from '@/store/action-types.js'
// import VuexPersistence from 'vuex-persist';
Vue.use(Vuex)

// const persist = new VuexPersistence({
//   storage:window.localStorage,
//   // reducer:(state)=>console.log(state)
// })

export default new Vuex.Store({
  state: {
    user:{},
    menuPermission:false,
    hasPermission:false
  },
  mutations: {
    setLogin(state,result){
      state.user = result;
      state.hasPermission = true;
    },
    validateUser(state,result){
      state.user = result;
      state.hasPermission = true;
    },
    [types.SET_MENU_LIST](state){
      state.menuPermission = true;
    }
  },
  actions: {
    // 登录接口
    async setLogin({commit},user){
      try{
        let result  =  await fetchUser(user);
        commit('setLogin',result);
        localStorage.setItem('token',result.token);
      }catch(e){
         return Promise.reject(e);
      }
    },
    // 检验是否已经登录
    async validateUser({commit}){
      try{
        let user = await isValidateUser();
        commit('validateUser',user);
      }catch(e){
        return Promise.reject(e);
     }
    }
  },
  modules: {
    home,
    course
  },
  // plugins:[persist.plugin]
 
})
